package com.starmark.gateway.auth.provider.web;

import com.starmark.auth.common.util.UserUtil;
import com.starmark.core.framework.base.AbstractController;
import com.starmark.core.framework.base.BaseTree;
import com.starmark.core.framework.util.BeanMapper;
import com.starmark.gateway.auth.provider.entity.GatewayAuthResource;
import com.starmark.gateway.auth.provider.service.IGatewayAuthResourceService;
import com.starmark.gateway.auth.provider.vo.GatewayAuthResourceTreeVo;
import com.starmark.gateway.auth.provider.vo.GatewayAuthResourceVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 系统资源 前端控制器
 * </p>
 *
 * @author starmark
 * @since 2019-04-21
 */
@RestController
@Api(value = "系统资源管理", description = "系统资源管理")
@RequestMapping("/gateway/auth/resource")
public class GatewayAuthResourceController extends AbstractController {
    @Autowired
    IGatewayAuthResourceService authResourceService;

    @ApiOperation(value = "查询系统资源结构树")
    @PostMapping(value = "/resourceTree")
    public List<GatewayAuthResourceTreeVo> resourceTree() {

        return BaseTree.build(BeanMapper.mapList(authResourceService.getResourceTree(UserUtil.getCurrentUser().getProjectCode()), GatewayAuthResourceTreeVo.class),
                null);
    }


    @ApiOperation(value = "保存与更新系统资源")
    @PostMapping
    public Object saveOrUpdate(@RequestBody GatewayAuthResourceVo gatewayAuthResourceVo) {
        this.authResourceService.saveOrUpdateResource(gatewayAuthResourceVo);
        return gatewayAuthResourceVo;
    }

    @ApiOperation(value = "系统资源详情")
    @GetMapping(value = "/{id}")
    public GatewayAuthResourceVo get(@PathVariable("id") String id) {
        GatewayAuthResource gatewayAuthResource = authResourceService.getById(id);
        GatewayAuthResourceVo gatewayAuthResourceVo = BeanMapper.map(gatewayAuthResource, GatewayAuthResourceVo.class);
        if (gatewayAuthResource.getParentId() != null) {
            gatewayAuthResourceVo.setParentName(authResourceService.getById(gatewayAuthResource.getParentId()).getName());
        }
        return gatewayAuthResourceVo;
    }


    @DeleteMapping(value = "/{id}")
    @ApiOperation(value = "删除系统资源")
    public void delete(@PathVariable("id") String id) {

        authResourceService.deleteResource(id);
    }
}
